<template>
  <div class="app-container">


    <!-- vxe检索数据组件 -->
    <search-form
      ref="searchForm "
      :formSearchData.sync="formSearchData"
      :deptCodeOptions="deptCodeOptions"
      :cpCodeOptions="cpCodeOptions"
      @dataDateChange="initTableCols"
      @searchEventEmit="searchEventEmit"
      @resetSearchEventEmit="resetSearchEventEmit"
    >
    </search-form>


    <!-- 表格组件 -->
    <ex-grid-table
      ref="exGridTable"
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading.sync="loading"
      :tableToolbar="tableToolbar"
      @handelDownloadEmit="handelDownloadEmit"
    >
    </ex-grid-table>

    <!-- 分页组件 -->
    <pagination
      v-show="tablePage.totalResult>0"
      :total="tablePage.totalResult"
      :page.sync="tablePage.currentPage"
      :limit.sync="tablePage.pageSize"
      @pagination="pageFindList"
    />


    <!-- 表单提价组件 -->
    <submit-form
      ref="submitForm"
      :dialogFormVisible.sync="dialogFormVisible"
      :dialogStatus="dialogStatus"
      :formSubmitData="formSubmitData"
      @handleFromUpdateDataEmit="handleFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
    >
    </submit-form>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'


import {findcompanylist, finddeptlist, findHeader, findlistData,} from './service/baseApi'

// 基础表格组件
import ExGridTable from '@/components/VxeTable/ExGridTableBB'
// 分页
import Pagination from '@/components/Pagination'
// 文章表单
import SubmitForm from './components/SubmitForm'
// 检索表单
import SearchForm from './components/SearchForm'
import resetFormSubmitData from '@/views/mixins/resetFormSubmitData'
import XEUtils from 'xe-utils'

export default {
  name: 'vxe-basetable',
  mixins: [resetFormSubmitData],
  components: {
    //PageHeaderLayout,
    ExGridTable,
    Pagination,
    SubmitForm,
    SearchForm
  },
  // 定义属性
  data() {
    const XEUtilsLocat = XEUtils.locat()
    const hostName = XEUtilsLocat.hostname
    const protocol = XEUtilsLocat.protocol
    return {
       /* host信息 */
      hostName: hostName,
      protocol: protocol,
      // 检索条件
      formSearchData: {
        data_date: [],
        dept_code: '',
        cp_code: ''
      },
      deptCodeOptions: [],
      cpCodeOptions: [],
      /* 表单相关 */
      dialogFormVisible: false, // 修改删除弹出框
      dialogStatus: '',
      // 表单数据对象
      formSubmitData: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published',
      },
      initFormSubmitData: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published',
      },
      /* 分页相关 */
      tablePage: {
        currentPage: 1, //当前页
        pageSize: 20,  // 每一页页数
        totalResult: 0
      },
      /* 表格相关 */
      tableColumn: [], // 表格字段
      loading: false, //表格loading特效
      tableData: [],  //表格数据
      tableToolbar: {
        slots: {
          tools: 'toolbar_tools2'
        }
      }
    } //datareturn-end

  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    handelDownloadEmit(){
      const isdatedate = (XEUtils.isArray(this.formSearchData.data_date) && this.formSearchData.data_date.length === 2)
      if (!isdatedate) {
        this.$message({
          message: '请先选择日期类型和日期区间！',
          type: 'warning'
        });
      }else{
        window.location.href = `${this.protocol}//${this.hostName}:7001/${process.env.VUE_APP_DATA_IO_URI_PARAM}/mlspecialCost/export?dept_code=${this.formSearchData.dept_code}&cp_code=${this.formSearchData.cp_code}&s_date=${(XEUtils.isArray(this.formSearchData.data_date) && this.formSearchData.data_date.length === 2) ? this.formSearchData.data_date[0] : ''}&e_date=${(XEUtils.isArray(this.formSearchData.data_date) && this.formSearchData.data_date.length === 2) ? this.formSearchData.data_date[1] : ''}`
      }
    },
    /* API数据操作相关 */
    findfinddeptlist() {
      finddeptlist().then(({data}) => {
        const deptCodeOptionsNotree = XEUtils.map(JSON.parse(JSON.stringify(data.rows)), item => {
          return {
            label: item.branch_name,
            value: item.branch_code,
            branch_code: parseInt(item.branch_code),
            parent_branch_code: parseInt(item.parent_branch_code),
          }
        })
        this.deptCodeOptions = XEUtils.toArrayTree(deptCodeOptionsNotree, {
          strict: true,
          parentKey: 'parent_branch_code',
          key: 'branch_code'
        })
      })
    },
    findfindcompanylist() {
      findcompanylist().then(({data}) => {
        this.cpCodeOptions = XEUtils.map(JSON.parse(JSON.stringify(data.rows)), item => {
          return {
            label: item.cp_name,
            value: item.cp_code,
          }
        })
      })
    },

    // 查询数据
    findList() {

      const isdatedate = (XEUtils.isArray(this.formSearchData.data_date) && this.formSearchData.data_date.length === 2)
      if (isdatedate) {
        this.loading = true
        // 请求表格数据
        findlistData({
          // page: this.tablePage.currentPage, // 当前页
          // pageSize: this.tablePage.pageSize, // 每页条数
          // ...this.formSearchData,  //检索条件
          dept_code: this.formSearchData.dept_code,
          cp_code: this.formSearchData.cp_code,
          s_date: (XEUtils.isArray(this.formSearchData.data_date) && this.formSearchData.data_date.length === 2) ? this.formSearchData.data_date[0] : '',
          e_date: (XEUtils.isArray(this.formSearchData.data_date) && this.formSearchData.data_date.length === 2) ? this.formSearchData.data_date[1] : '',
        }).then(({data}) => {
          console.log('response:....', data);
          // 给表格数据赋值
          this.tableData = data.rows
          // 给分页总数赋值
          // this.tablePage.totalResult = data.total
          // 关闭加载特效
          setTimeout(() => {
            this.loading = false
          }, 0.3 * 1000)
        })

      } else {
        this.$message({
          message: '请先选择日期类型和日期区间！',
          type: 'warning'
        });
      }


    },
    /* 分页组件相关 */
    // 分页事件（页码切换，每页页数切换）
    pageFindList() {
      this.findList()
    },
    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols(dataDate) {
      this.loading = true
      if (XEUtils.isArray(dataDate) && dataDate.length === 2) {
        findHeader({
          dept_code: this.formSearchData.dept_code,
          cp_code: this.formSearchData.cp_code,
          s_date: (XEUtils.isArray(dataDate) && dataDate.length === 2) ? dataDate[0] : '',
          e_date: (XEUtils.isArray(dataDate) && dataDate.length === 2) ? dataDate[1] : '',
        }).then(({data}) => {
          this.tableColumn = data.rows;
          this.tableData = []
          setTimeout(() => {
            this.loading = false
          }, 0.3 * 1000)
        })
      }

      // const tabCols = [  //动态增加的字段 传进来的
      //   // { type: 'seq', width: 60, fixed: null },
      //   // { type: 'checkbox', width: 50, fixed: null },
      //   {
      //     title: '基本信息',
      //     children: [
      //       {field: 'title', title: '标题', width: 200, showOverflow: true, fixed: 'left'},
      //       {field: 'title', title: '标题', width: 200, showOverflow: true},
      //       {field: 'title', title: '标题', width: 200, showOverflow: true},
      //       {field: 'title', title: '标题', width: 200, showOverflow: true},
      //       {field: 'title', title: '标题', width: 200, showOverflow: true},
      //       {field: 'pic_title_pc', title: 'pc封面图', width: 300},
      //     ]
      //   },

      //   {field: 'created_at', title: '更新时间', width: 200},
      //   {field: 'updated_at', title: '修改时间', width: 200},
      //   {
      //     field: 'author', title: '作者', width: 300, formatter(obj) {
      //       console.log('formatterformatter', obj);
      //       if (obj.cellValue === 0) {
      //         return "admin"
      //       } else {
      //         return "无名"
      //       }
      //     }
      //   }
      // ]
      // this.tableColumn = tabCols;
    },
    // 表格工具组-多选删除
    handleRemoveEmit(selectRecords) {
      console.log("AJAX请求删除记录");
      this.$refs.exBaseTable.$refs.xTable.removeCheckboxRow()
      this.findList()
    },
    // 表格工具组-新增表单弹窗（需要表单组件）
    handleCreateEmit(type) {
      // 重置表单内容
      this.resetFormSubmitData()
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 行内按钮-修改数据弹窗（需要表单组件）
    handleUpdateEmit(row, type) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 单行删除
    handleRmoveColEmit(row) {
      console.log("AJAX 请求删除单行数据");
      this.$refs.exBaseTable.$refs.xTable.remove(row)
    },

    /* 表单组件相关 */
    // 更新
    handleFromUpdateDataEmit() {
      console.log("this.formSubmitDatathis.formSubmitDatathis.formSubmitDatathis.formSubmitData", this.formSubmitData);
      console.log("表单组件相关:此处运行更新数据操作api等");
    },
    // 增加
    handleFromCreateDataEmit() {
      console.log("this.formSubmitDatathis.formSubmitDatathis.formSubmitDatathis.formSubmitData", this.formSubmitData);
      console.log("表单组件相关:此处运行添加数据操作api等");
    },

    /* 检索相关 */
    // 检索
    searchEventEmit() {
      this.tablePage.currentPage = 1
      console.log("searchEventEmit", this.formSearchData);
      this.findList()
    },
    // 重置
    resetSearchEventEmit() {
      // 重置代码...
      // console.log("resetSearchEventEmit", this.formSearchData);
      // this.tablePage.currentPage = 1
      // this.findList()
      setTimeout(() => {
        this.loading = false
      }, 0.3 * 1000)
    },
    footerMethodEmit({columns, data}) {
      console.log('columnscolumns', columns);
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['title', 'pic_title_pc'].includes(column.property)) {
            // return XEUtils.sum(data, column.property)
            return '123'
          }
          return null
        }),
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '平均'
          }
          if (['age', 'rate'].includes(column.property)) {
            return XEUtils.mean(data, column.property)
          }
          return null
        })
      ]
    },
    footerMethod({columns, data}) {

      // return this.$emit("footerMethodEmit",{columns,data})
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['title', 'pic_title_pc'].includes(column.property)) {
            // return XEUtils.sum(data, column.property)
            return '123'
          }
          return null
        }),
        // columns.map((column, columnIndex) => {
        //   if (columnIndex === 0) {
        //     return '平均'
        //   }
        //   if (['age', 'rate'].includes(column.property)) {
        //     return XEUtils.mean(data, column.property)
        //   }
        //   return null
        // })
      ]

    }


  }, //method-end
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    // 测试功能-下拉分页表格
    // this.keyupEvent4()
    // 初始化表格字段
    // await this.initTableCols()
    // 初始化表格数据
    // this.findList()
    await this.findfinddeptlist()

    await this.findfindcompanylist()

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>


.my-dropdown4 {
  width: 600px;
  height: 300px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>